package cn.yuan.server;

import cn.yuan.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tao
 */
public class EchoServer {

    private final int port;
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        int port;
        if (args.length == 0) {
            port = 8899;
        } else {
            port = Integer.parseInt(args[1]);
        }
        LOGGER.info("服务监听端口：[{}]", port);
        new EchoServer(port).start();

    }

    private void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            // 不会执行到这里。
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            LOGGER.error("服务启动失败", e);
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException ex) {
                LOGGER.error("事件循环终止失败", ex);
            }

        }
    }


}
